import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Toast } from 'antd-mobile';
import VConsole from 'vconsole';
import Routers from './routers';
import reportWebVitals from './reportWebVitals';
import NewMessageTopBar from './components/NewMessageTopBar';
import { observer } from "mobx-react-lite";
import { MySdkStoreContext, mySdkStore } from './context';

import './index.scss';

import { globalJump, isHideSomeFunctions, loadScript } from './utils';

let isInit = false;
const { AlipayCcmImSdk } = window;

function initSDK () {
  if (!window.initSDK && !isInit) {
    isInit = true;
    window.initSDK = new AlipayCcmImSdk(mySdkStore.mockConfig);
  }

  return window.initSDK;
}

const App = observer(() => {
  const [loading, setLoading] = useState(true);
  // const [newMessageTopBarProps, setNewMessageTopBarProps] = useState({ visible: false });
  
  useEffect(() => {
    const isDebug = window.location.search.indexOf('debug') > -1;
    if (isDebug) {
      new VConsole({ maxLogNumber: 1000 });
    }

    //加载高德地图资源，本资源为个人开发者权限
    loadScript('//webapi.amap.com/maps?v=2.0&key=bdc83d491ce5519b3ba7c15ef82d4c6c&plugin=AMap.ToolBar');
    loadScript('//webapi.amap.com/ui/1.1/main.js?v=1.1.1')
    window._AMapSecurityConfig = {
      securityJsCode:'6f840f4fd8501a8d3e527ac45f0a8b6e',
    }
  }, [])

  useEffect(async () => {
    if (mySdkStore.showLogin) {
      setLoading(false);
      globalJump("#/loginByUserId");
      return;
    }
    if(!mySdkStore.sdk) {
      const newSdk = initSDK();

      newSdk.onError = (error) => {
        const { code, message } = error;
        Toast.show(message);
      };
      newSdk.onInitOk = async () => {
        mySdkStore.setVal('sdkInitOk', true);
        // mySdkStore.setVal('sdk', sdk);
        mySdkStore.setVal('isHideSomeFunctions', isHideSomeFunctions());
        setTimeout(() => setLoading(false), 1500);
      };

      newSdk.onCustomCmdMsg = (res) => {
        const utf8decoder = new TextDecoder();
        const { cid, content, from, to } = res;
        const { data, dataType } = content;
        const customData = utf8decoder.decode(data);
      }

      newSdk.onKicked = () => {
        Toast.show({
          icon: 'fail',
          content: '当前用户已在其他端登录！'
        });
        setTimeout(() => globalJump("#/loginByUserId"), 1000);
      }

      newSdk.onEmojiInitOk = () => {
        newSdk.getEmojiById("all").then(data => {
          mySdkStore.setVal('emojiList', data);
        });
      };

      newSdk.connect();

      mySdkStore.setVal('sdk', newSdk);
    }
  }, []);

  // const goToMeetingPage = () => {
  //   history.push({ pathname: `/meetingDetail/${mySdkStore.currentMeetingInfo.cid}` });
  // }

  return loading ? <div style={{ margin: '50vw auto', textAlign: 'center'}}>加载中...</div> : <MySdkStoreContext.Provider value={mySdkStore}>
    {/* { mySdkStore.newMessageTopBarProps.visible && <NewMessageTopBar {...newMessageTopBarProps} />} */}
    <NewMessageTopBar />
    <Routers mySdkStore={mySdkStore} />
  </MySdkStoreContext.Provider>
})

ReactDOM.render(<App />,  document.getElementById('root'))

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
